<!DOCTYPE html>
<html lang="en">
    <!-- title -->




<!-- keywords -->




<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" >
    <meta name="author" content="驿路星辰">
    <meta name="renderer" content="webkit">
    <meta name="copyright" content="驿路星辰">
    
    <meta name="keywords" content="算法,Swift,Dart,iOS,Flutter,C++">
    
    <meta name="description" content="">
    <meta name="description" content="我想说这真的是一篇非常非常好的文章，它通过对一个实例的API的优化，教会我们如何写出优美简洁的Swift的函数式代码。但是这个文章是视频中作者的口述，所以翻译过程中难免有不当之处。大家可以对着视频和原文进行观看和对比。 原文地址 介绍Swift第一次被公布的一周后，我写了一篇名为“Swift不是函数式”的博文。两年后，Swift仍然不是函数式。这篇文章并没有对此进行阐述，而是将讨论函数式语言几十年">
<meta property="og:type" content="article">
<meta property="og:title" content="【译】Swift和函数式编程的精髓">
<meta property="og:url" content="http://kurumi.gitee.io/shanks/2019/10/11/swift-function-program/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="我想说这真的是一篇非常非常好的文章，它通过对一个实例的API的优化，教会我们如何写出优美简洁的Swift的函数式代码。但是这个文章是视频中作者的口述，所以翻译过程中难免有不当之处。大家可以对着视频和原文进行观看和对比。 原文地址 介绍Swift第一次被公布的一周后，我写了一篇名为“Swift不是函数式”的博文。两年后，Swift仍然不是函数式。这篇文章并没有对此进行阐述，而是将讨论函数式语言几十年">
<meta property="og:locale" content="en_US">
<meta property="article:published_time" content="2019-10-11T01:58:08.000Z">
<meta property="article:modified_time" content="2022-05-02T05:51:49.850Z">
<meta property="article:author" content="驿路星辰">
<meta name="twitter:card" content="summary">
    <meta http-equiv="Cache-control" content="no-cache">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
    
    <title>【译】Swift和函数式编程的精髓 · iOS</title>
    <style type="text/css">
    @font-face {
        font-family: 'Oswald-Regular';
        src: url("/shanks/font/Oswald-Regular.ttf");
    }

    body {
        margin: 0;
    }

    header,
    footer,
    .back-top,
    .sidebar,
    .container,
    .site-intro-meta,
    .toc-wrapper {
        display: none;
    }

    .site-intro {
        position: relative;
        z-index: 3;
        width: 100%;
        /* height: 30vh; */
        overflow: hidden;
    }

    .site-intro-placeholder {
        position: absolute;
        z-index: -2;
        top: 0;
        left: 0;
        width: calc(100% + 300px);
        height: 100%;
        background: repeating-linear-gradient(-45deg, #444 0, #444 80px, #333 80px, #333 160px);
        background-position: center center;
        transform: translate3d(-226px, 0, 0);
        animation: gradient-move 2.5s ease-out 0s infinite;
    }

    @keyframes gradient-move {
        0% {
            transform: translate3d(-226px, 0, 0);
        }
        100% {
            transform: translate3d(0, 0, 0);
        }
    }

</style>

    <link rel="preload" href= "/shanks/css/style.css?v=20180824" as="style" onload="this.onload=null;this.rel='stylesheet'" />
    <link rel="stylesheet" href= "/shanks/css/mobile.css?v=20180824" media="(max-width: 980px)">
    
    <link rel="preload" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.2.5/jquery.fancybox.min.css" as="style" onload="this.onload=null;this.rel='stylesheet'" />
    
    <!-- /*! loadCSS. [c]2017 Filament Group, Inc. MIT License */
/* This file is meant as a standalone workflow for
- testing support for link[rel=preload]
- enabling async CSS loading in browsers that do not support rel=preload
- applying rel preload css once loaded, whether supported or not.
*/ -->
<script>
(function( w ){
	"use strict";
	// rel=preload support test
	if( !w.loadCSS ){
		w.loadCSS = function(){};
	}
	// define on the loadCSS obj
	var rp = loadCSS.relpreload = {};
	// rel=preload feature support test
	// runs once and returns a function for compat purposes
	rp.support = (function(){
		var ret;
		try {
			ret = w.document.createElement( "link" ).relList.supports( "preload" );
		} catch (e) {
			ret = false;
		}
		return function(){
			return ret;
		};
	})();

	// if preload isn't supported, get an asynchronous load by using a non-matching media attribute
	// then change that media back to its intended value on load
	rp.bindMediaToggle = function( link ){
		// remember existing media attr for ultimate state, or default to 'all'
		var finalMedia = link.media || "all";

		function enableStylesheet(){
			link.media = finalMedia;
		}

		// bind load handlers to enable media
		if( link.addEventListener ){
			link.addEventListener( "load", enableStylesheet );
		} else if( link.attachEvent ){
			link.attachEvent( "onload", enableStylesheet );
		}

		// Set rel and non-applicable media type to start an async request
		// note: timeout allows this to happen async to let rendering continue in IE
		setTimeout(function(){
			link.rel = "stylesheet";
			link.media = "only x";
		});
		// also enable media after 3 seconds,
		// which will catch very old browsers (android 2.x, old firefox) that don't support onload on link
		setTimeout( enableStylesheet, 3000 );
	};

	// loop through link elements in DOM
	rp.poly = function(){
		// double check this to prevent external calls from running
		if( rp.support() ){
			return;
		}
		var links = w.document.getElementsByTagName( "link" );
		for( var i = 0; i < links.length; i++ ){
			var link = links[ i ];
			// qualify links to those with rel=preload and as=style attrs
			if( link.rel === "preload" && link.getAttribute( "as" ) === "style" && !link.getAttribute( "data-loadcss" ) ){
				// prevent rerunning on link
				link.setAttribute( "data-loadcss", true );
				// bind listeners to toggle media back
				rp.bindMediaToggle( link );
			}
		}
	};

	// if unsupported, run the polyfill
	if( !rp.support() ){
		// run once at least
		rp.poly();

		// rerun poly on an interval until onload
		var run = w.setInterval( rp.poly, 500 );
		if( w.addEventListener ){
			w.addEventListener( "load", function(){
				rp.poly();
				w.clearInterval( run );
			} );
		} else if( w.attachEvent ){
			w.attachEvent( "onload", function(){
				rp.poly();
				w.clearInterval( run );
			} );
		}
	}


	// commonjs
	if( typeof exports !== "undefined" ){
		exports.loadCSS = loadCSS;
	}
	else {
		w.loadCSS = loadCSS;
	}
}( typeof global !== "undefined" ? global : this ) );
</script>

    <link rel="icon" href= "/shanks/assets/favicon.ico" />
    <link rel="preload" href="https://cdn.jsdelivr.net/npm/webfontloader@1.6.28/webfontloader.min.js" as="script" />
    <link rel="preload" href="https://cdn.jsdelivr.net/npm/jquery@3.3.1/dist/jquery.min.js" as="script" />
    <link rel="preload" href="/shanks/scripts/main.js" as="script" />
    <link rel="preload" as="font" href="/shanks/font/Oswald-Regular.ttf" crossorigin>
    <link rel="preload" as="font" href="https://at.alicdn.com/t/font_327081_1dta1rlogw17zaor.woff" crossorigin>
    
    <!-- fancybox -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.2.5/jquery.fancybox.min.js" defer></script>
    <!-- 百度统计  -->
    
    <!-- 谷歌统计  -->
    
<meta name="generator" content="Hexo 4.2.1"></head>

    
        <body class="post-body">
    
    
<header class="header">

    <div class="read-progress"></div>
    <div class="header-sidebar-menu">&#xe775;</div>
    <!-- post页的toggle banner  -->
    
    <div class="banner">
            <div class="blog-title">
                <a href="/shanks/" >驿路星辰的博客</a>
            </div>
            <div class="post-title">
                <a href="#" class="post-name">【译】Swift和函数式编程的精髓</a>
            </div>
    </div>
    
    <a class="home-link" href=/shanks/>驿路星辰的博客</a>
</header>
    <div class="wrapper">
        <div class="site-intro" style="







height:50vh;
">
    
    <!-- 主页  -->
    
    
    <!-- 404页  -->
            
    <div class="site-intro-placeholder"></div>
    <div class="site-intro-img" style="background-image: url(/shanks/intro/post-bg.jpg)"></div>
    <div class="site-intro-meta">
        <!-- 标题  -->
        <h1 class="intro-title">
            <!-- 主页  -->
            
            【译】Swift和函数式编程的精髓
            <!-- 404 -->
            
        </h1>
        <!-- 副标题 -->
        <p class="intro-subtitle">
            <!-- 主页副标题  -->
            
            
            <!-- 404 -->
            
        </p>
        <!-- 文章页meta -->
        
            <div class="post-intros">
                <!-- 文章页标签  -->
                
                
                    <div class="post-intro-read">
                        <span>Word count: <span class="post-count word-count">3.1k</span>Reading time: <span class="post-count reading-time">11 min</span></span>
                    </div>
                
                <div class="post-intro-meta">
                    <span class="post-intro-calander iconfont-archer">&#xe676;</span>
                    <span class="post-intro-time">2019/10/11</span>
                    
                    <span id="busuanzi_container_page_pv" class="busuanzi-pv">
                        <span class="iconfont-archer">&#xe602;</span>
                        <span id="busuanzi_value_page_pv"></span>
                    </span>
                    
                    <span class="shareWrapper">
                        <span class="iconfont-archer shareIcon">&#xe71d;</span>
                        <span class="shareText">Share</span>
                        <ul class="shareList">
                            <li class="iconfont-archer share-qr" data-type="qr">&#xe75b;
                                <div class="share-qrcode"></div>
                            </li>
                            <li class="iconfont-archer" data-type="weibo">&#xe619;</li>
                            <li class="iconfont-archer" data-type="qzone">&#xe62e;</li>
                            <li class="iconfont-archer" data-type="twitter">&#xe634;</li>
                            <li class="iconfont-archer" data-type="facebook">&#xe67a;</li>
                        </ul>
                    </span>
                </div>
            </div>
        
    </div>
</div>
        <script>
 
  // get user agent
  var browser = {
    versions: function () {
      var u = window.navigator.userAgent;
      return {
        userAgent: u,
        trident: u.indexOf('Trident') > -1, //IE内核
        presto: u.indexOf('Presto') > -1, //opera内核
        webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
        gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
        mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
        ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
        android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
        iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者安卓QQ浏览器
        iPad: u.indexOf('iPad') > -1, //是否为iPad
        webApp: u.indexOf('Safari') == -1, //是否为web应用程序，没有头部与底部
        weixin: u.indexOf('MicroMessenger') == -1, //是否为微信浏览器
        uc: u.indexOf('UCBrowser') > -1 //是否为android下的UC浏览器
      };
    }()
  }
  console.log("userAgent:" + browser.versions.userAgent);

  // callback
  function fontLoaded() {
    console.log('font loaded');
    if (document.getElementsByClassName('site-intro-meta')) {
      document.getElementsByClassName('intro-title')[0].classList.add('intro-fade-in');
      document.getElementsByClassName('intro-subtitle')[0].classList.add('intro-fade-in');
      var postIntros = document.getElementsByClassName('post-intros')[0]
      if (postIntros) {
        postIntros.classList.add('post-fade-in');
      }
    }
  }

  // UC不支持跨域，所以直接显示
  function asyncCb(){
    if (browser.versions.uc) {
      console.log("UCBrowser");
      fontLoaded();
    } else {
      WebFont.load({
        custom: {
          families: ['Oswald-Regular']
        },
        loading: function () {  //所有字体开始加载
          // console.log('loading');
        },
        active: function () {  //所有字体已渲染
          fontLoaded();
        },
        inactive: function () { //字体预加载失败，无效字体或浏览器不支持加载
          console.log('inactive: timeout');
          fontLoaded();
        },
        timeout: 5000 // Set the timeout to two seconds
      });
    }
  }

  function asyncErr(){
    console.warn('script load from CDN failed, will load local script')
  }

  // load webfont-loader async, and add callback function
  function async(u, cb, err) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (cb) { o.addEventListener('load', function (e) { cb(null, e); }, false); }
    if (err) { o.addEventListener('error', function (e) { err(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }

  var asyncLoadWithFallBack = function(arr, success, reject) {
      var currReject = function(){
        reject()
        arr.shift()
        if(arr.length)
          async(arr[0], success, currReject)
        }

      async(arr[0], success, currReject)
  }

  asyncLoadWithFallBack([
    "https://cdn.jsdelivr.net/npm/webfontloader@1.6.28/webfontloader.min.js", 
    "https://cdn.bootcss.com/webfont/1.6.28/webfontloader.js",
    "/shanks/lib/webfontloader.min.js"
  ], asyncCb, asyncErr)
</script>        
        <img class="loading" src="/shanks/assets/loading.svg" style="display: block; margin: 6rem auto 0 auto; width: 6rem; height: 6rem;" />
        <div class="container container-unloaded">
            <main class="main post-page">
    <article class="article-entry">
        <p>我想说这真的是一篇非常非常好的文章，它通过对一个实例的API的优化，教会我们如何写出优美简洁的Swift的函数式代码。但是这个文章是视频中作者的口述，所以翻译过程中难免有不当之处。大家可以对着视频和原文进行观看和对比。</p>
<p><a href="https://academy.realm.io/posts/tryswift-rob-napier-swift-legacy-functional-programming/" target="_blank" rel="noopener">原文地址</a></p>
<h3 id="介绍"><a href="#介绍" class="headerlink" title="介绍"></a>介绍</h3><p>Swift第一次被公布的一周后，我写了一篇名为“<a href="http://robnapier.net/swift-is-not-functional" target="_blank" rel="noopener">Swift不是函数式</a>”的博文。两年后，Swift仍然不是函数式。这篇文章并没有对此进行阐述，而是将讨论函数式语言几十年来的经验和研究，我们可以用自己快速的方式将这些经验和研究带入Swift。</p>
<h4 id="什么是函数式编程"><a href="#什么是函数式编程" class="headerlink" title="什么是函数式编程"></a>什么是函数式编程</h4><p>它是单子、仿函数、haskell和优雅的代码。</p>
<p>函数式编程不是一种语言或语法，而是一种思考问题的方式。函数式编程在我们有<code>单子</code>之前已经存在了几十年。函数式编程是一种思考如何分解问题，然后以结构化的方式将它们重新组合在一起的方法。</p>
<p>让我们从swift中的一个简单示例开始。</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> persons: [<span class="type">Person</span>] = []</span><br><span class="line"><span class="keyword">for</span> name <span class="keyword">in</span> names &#123;</span><br><span class="line">    <span class="keyword">let</span> person = <span class="type">Person</span>(name: name)</span><br><span class="line">    <span class="keyword">if</span> person.isValid &#123;</span><br><span class="line">        persons.append(person)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这是一个简单的循环，它做两件事：将<code>name</code>转换成<code>Person</code>，然后将这些人放入一个有效的数组中。很简单，但这里有很多事情。为了理解发生了什么，你需要在头脑中执行这个。你需要思考，“这个数组是做什么的？“</p>
<p>它看起来很简单，但可能会更简单。我们可以把问题分开。我们可以把东西拆开。<br>我们现在有两个循环，每个循环做的更少。每一个都很简单，更简单的代码让我们找到模式：创建一个数组，遍历一些值，对每个值执行一些操作，然后在最后将它们放到另一个数组中。</p>
<p>当你有一些事情做了很多次，你可能应该提取函数-Swift有一个，它被称为<code>map</code>。<code>map</code>将某物的列表转换为其他某物的列表。重要的是它说明了它的含义：可能<code>persons</code>是<code>names</code>到<code>person</code>的映射。这是一份根据人名列出的名单。我们不必在头脑中执行任何东西，他就在代码中表述我们的意思。</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> possiblePersons = names.<span class="built_in">map</span>(<span class="type">Person</span>.<span class="keyword">init</span>)</span><br><span class="line"><span class="keyword">let</span> persons = possiblePersons.<span class="built_in">filter</span> &#123; $<span class="number">0</span>.isValid &#125;</span><br></pre></td></tr></table></figure>
<p>另一个循环也是一个非常常见的模式：它有一个名为“filter”的方法。filter接受一个谓词，它是一个返回<code>bool</code>的函数。它使用函数给我们返回有效的数据。我们可以把这些结合在一起，从而获得<code>possiblePersons</code>，然后把他们加入我们的过滤器。</p>
<p>从七行代码到两行代码。另外，我们可以重新组合它们：这些都是我们可以重新组合起来的值。我们用链式把他们进行组合。</p>
<p>它很容易阅读，我们可以一行一行地阅读。</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> persons = names</span><br><span class="line">    .<span class="built_in">map</span>(<span class="type">Person</span>.<span class="keyword">init</span>)</span><br><span class="line">    .<span class="built_in">filter</span> &#123; $<span class="number">0</span>.isValid &#125;</span><br></pre></td></tr></table></figure>
<p>它十分易学并且很容易适应这种方式。在这样的例子中你不必再写一个for循环了。</p>
<h3 id="函数式工具"><a href="#函数式工具" class="headerlink" title="函数式工具"></a>函数式工具</h3><p>1977年，John Backus（协助发明了Fortran 和 Algol）获得了图灵奖，发表演讲“编程能从冯诺依曼风格中解放出来吗？“我喜欢这个标题。“冯·诺依曼风格”是指Fortran和Algol。</p>
<p>这篇论文是他为发明它们而做的声明。他表示命令式编程，一步一步地改变某种状态，直到获得你想要的最终状态。当他说“函数式”的时候，那并不是指我们今天所说的函数式，但他启发了许多函数式研究人员去研究和学习。</p>
<p>这篇论文引起了我的兴趣，我们可以回到swift：我们如何将复杂的事情分解成简单的事情。把这些简单的东西泛化，然后用一些规则把它们粘在一起，比如代数。</p>
<p>代数是一套规则，用来把事物组合在一起，把它们拆开，然后转换它们。我们可以想出可以用来操纵程序的规则。我们已经做到了：我们做了一个循环，我们把它分解成两个简单的循环，找到每一个循环的通用形式，然后使用链式将它们重新组合在一起。当haskell程序员第一次遇到swift时，他们往往会感到沮丧，因为试着做它们在Haskell语言中做的事。</p>
<p>在haskell中，与几乎所有的函数式语言一样，组成的基本单元是函数。有很多漂亮的方法来组合函数。我可以通过将<code>foldr</code>函数和<code>+</code>函数粘合在一起，并将其初始值设为0，来创建一个名为sum的新函数。不管你读起来是否舒服，只要你这样做了，它就相当漂亮了。</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> sum = foldr (+) <span class="number">0</span></span><br><span class="line">  sum [<span class="number">1</span>..<span class="number">10</span>]</span><br></pre></td></tr></table></figure>
<p>你可以用swift来做，但是它会很难看，而且它不能很好地工作，因为你在用错误单元组合它们。swift不是函数式。</p>
<p>swift中的组成单位是类型。类、结构、枚举和协议，这些都是可以组合的。我们通常把两种类型粘在一起。通过实现一个函数并将它们粘在一起，我们可以用更简单的片段来构建它们。</p>
<p>swift中另一种非常常见的构图是将类型放在语境中。你最常用的是<code>optionals</code>。可选类型是根据语境确定的，在语境中可能有值也可能没有值。这是一个与类型相关的小信息：它是否存在？这就是语境的含义。添加语境比其他跟踪额外信息的方法强大得多。</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">extension</span> <span class="title">MyStruct</span>&lt;<span class="title">T</span>&gt;: <span class="title">Sequence</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">func</span> <span class="title">makeIterator</span><span class="params">()</span></span> -&gt; <span class="type">AnyIterator</span>&lt;<span class="type">T</span>&gt; &#123;</span><br><span class="line"><span class="keyword">return</span> ... &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>我们可以跟踪一个事实，即不存在整数，或者根本不存在值，这是因为我们会从-1这样的整数中窃取一个值，这意味着没有值。但是现在你必须到处测试，这是丑陋的，容易出错的，编译器不能帮你。</p>
<p>如果我们将整数改为可选的，这时编译器可以帮助您。你有这样的语境“它存在吗，它不存在吗，我可以帮助你确保你不会忘记这一点。”如果你曾经使用过-1，很容易忘记检查，然后你的程序变得不可控了。</p>
<h3 id="例子"><a href="#例子" class="headerlink" title="例子"></a>例子</h3><p>让我们建立一个更复杂的例子。</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">login</span><span class="params">(username: String, password: String,</span></span></span><br><span class="line"><span class="function"><span class="params">           completion: <span class="params">(String?, Error?)</span></span></span> -&gt; <span class="type">Void</span>)</span><br><span class="line">login(username: <span class="string">"rob"</span>, password: <span class="string">"s3cret"</span>) &#123;</span><br><span class="line">    (token, error) <span class="keyword">in</span></span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">let</span> token = token &#123;</span><br><span class="line">        <span class="comment">// success</span></span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> <span class="keyword">let</span> error = error &#123;</span><br><span class="line"><span class="comment">// failure &#125;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这是一个非常常见的API。我们有一个带有<code>username</code>和<code>password</code>参数的<code>login</code>函数，在某个时刻，它将返回一个<code>token</code>和一个可能的错误。我认为我们可以通过考虑语境做得更好。</p>
<p><strong>第一个问题</strong> 是这个<code>completion</code>。我说它是一个<code>string</code>，是什么样的<code>string</code>。她是一个<code>token</code>.我可以给它贴个标签，但那没用。在swift中，标签不是类型的一部分。即使我这么做了，还是这个<code>string</code>。字符串可以是指很多东西。</p>
<p><code>Tokens</code>有规则：例如，它们可能必须是固定长度，或者不能为空。这些都是可以用字符串做的，但不能用<code>tokens</code>。我们希望有更多关于<code>token</code>的上下文；它有规则，所以我们希望捕获这些规则。我们可以做到，我们可以给它更多的结构。这就是为什么它被称为<code>struct</code>。</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">Token</span> </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> string: <span class="type">String</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>我把字符串放入结构体中。这不会花费任何成本，也不会导致间接或任何额外的内存使用，但现在我可以对此设置规则。</p>
<p>你只能用特定的字符串来构造它们。我可以在上面加上一些扩展，这样就没有必要用任意的字符串了。这要好多了，我可以对所有类型都这样做；字符串当然没问题，也可以是字典、数组和整数类型。</p>
<p>当您拥有这些类型时，您可以将它们提升到上下文中，并控制可以放在它们上的内容。你可以控制他表达的意思。我不需要标签或注释，因为第一个参数显然是一个<code>token</code>，因为它的类型是<code>Token</code>。</p>
<p><strong>第二个问题</strong> 是我们要传递<code>username</code>和<code>password</code>。在大多数有这些的程序中，您总是将它们一起传递；<code>password</code>本身尤其无用。我想创建一个规则，允许我用“and”组合用户名和密码，所以我需要一个“and”类型。我们有一个，它又是一个结构。</p>
<h3 id="“AND”类型"><a href="#“AND”类型" class="headerlink" title="“AND”类型"></a>“AND”类型</h3><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">Credential</span> </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> username: <span class="type">String</span></span><br><span class="line">  <span class="keyword">var</span> password: <span class="type">String</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>结构体是”and”类型。 <code>Credential</code> 是由<code>username</code>和<code>password</code>组成.  “and”类型被称为 “生产类型”.<br>我鼓励你大声说出来。例如：“凭证是用户名和密码。”这有意义吗？如果它没有意义，也许它是错误的类型，或者你创建它是错误的。</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">login</span><span class="params">(credential: Credential,</span></span></span><br><span class="line"><span class="function"><span class="params">           completion: <span class="params">(Token?, Error?)</span></span></span> -&gt; <span class="type">Void</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> credential = <span class="type">Credential</span>(username: <span class="string">"rob"</span>,</span><br><span class="line">                            password: <span class="string">"s3cret"</span>)</span><br><span class="line">login(credential: credential) &#123; (token, error) <span class="keyword">in</span></span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">let</span> token = token &#123;</span><br><span class="line">        <span class="comment">// success</span></span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> <span class="keyword">let</span> error = error &#123;</span><br><span class="line"><span class="comment">// failure &#125;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>现在我们可以交换<code>Credential</code>，而不是<code>username</code>和<code>password</code>：这也使得我们的签名更短更清晰。我们还提供了许多不错的可能性：在<code>Credentials</code>上添加扩展，在其他类型的规则下交换它们。也许我们想要10次<code>password</code>，或者<code>access token</code>，或者<code>facebook</code>或者<code>google</code>等等。现在，我不需要更改代码的任何其他部分，因为我只是传递<code>credentials</code>。</p>
<p>不过，它也有问题。我们通过了元组(Token?, Error?) –元组是“and”类型。它们是匿名结构。我们的意思是“也许是token，也许是error”？有四种可能性：两者都有，或者两者都没有，或者一个或另一个。只有两种可能性是有意义的。如果我得到了一个<code>token</code>和<code>error</code>？这是一个错误条件吗？我需要一个致命的错误吗？我需要忽略它吗？你需要考虑一下这个问题，并可能针对它编写测试。</p>
<h3 id="“OR”-Type-Sum"><a href="#“OR”-Type-Sum" class="headerlink" title="“OR” Type (Sum)"></a>“OR” Type (Sum)</h3><p>问题是你不是说“也许”什么的-你是指一个<code>token</code>或一个<code>error</code>。我们有可以使用的“或”类型吗？</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">enum</span> <span class="title">Result</span>&lt;<span class="title">Value</span>&gt; </span>&#123;</span><br><span class="line">    <span class="keyword">case</span> success(<span class="type">Value</span>)</span><br><span class="line">    <span class="keyword">case</span> failure(<span class="type">Error</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>It is an enum - enums are “or” types (this or that), whereas structs are “and” types (this and that). Like “and” types are called “product types”, “or” types are called “sum types”.<br>这是一个枚举 - <code>enums</code>是 “or”类型，就像结构体是“and”类型。正如“and”类型被称作“生产类型”，“or”类型被称为“和类型”</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">login</span><span class="params">(credential: Credential,</span></span></span><br><span class="line"><span class="function"><span class="params">           completion: <span class="params">(Result&lt;Token&gt;)</span></span></span> -&gt; <span class="type">Void</span>)</span><br><span class="line">login(credential: credential) &#123; result <span class="keyword">in</span></span><br><span class="line">    <span class="keyword">switch</span> result &#123;</span><br><span class="line">    <span class="keyword">case</span> .success(<span class="keyword">let</span> token): <span class="comment">// success</span></span><br><span class="line">    <span class="keyword">case</span> .failure(<span class="keyword">let</span> error): <span class="comment">// failure</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>我想建立这个<code>result</code>类型。这让我很困扰，因为它不是内置在swift中的。它很容易建造。我们将提升我们的值，给它更多的语境。它从一种值转变为一个成功的值。</p>
<p>我们的错误变成一个失败的错误，我们有更多的语境。如果我们将<code>result</code>、生成的<code>token</code>扔进我们的api中，那么我们必须针对所有这些情况编写测试来保证所有不可能的情况都会消失。我们不必担心他们，因为他们是不可能的。我希望错误不可能，而不是编写测试用例。</p>
<p>我喜欢这个API。我用<code>credential</code>登录，它会给我一个生成的<code>token</code>。</p>
<h3 id="这个课程"><a href="#这个课程" class="headerlink" title="这个课程"></a>这个课程</h3><p>这是函数式编程的真正精髓，也是我们应该带给swift的：复杂的事情可以分解成更小、更简单的事情。</p>
<p>我们可以为这些简单的事情找到通用的解决方案，我们可以使用一致的规则将这些简单的事情重新组合起来，让我们对我们的程序进行推理。这使得编译器更容易查出bug，我认为70年代的<code>John Backus</code>完全同意这一点。把它拆了，把它造起来。</p>

    </article>
    <!-- license  -->
    
        <div class="license-wrapper">
            <p>Author：<a href="http://kurumi.gitee.io/shanks">驿路星辰</a>
            <p>原文链接：<a href="http://kurumi.gitee.io/shanks/2019/10/11/swift-function-program/">http://kurumi.gitee.io/shanks/2019/10/11/swift-function-program/</a>
            <p>发表日期：<a href="http://kurumi.gitee.io/shanks/2019/10/11/swift-function-program/">October 11th 2019</a>
            <p>更新日期：<a href="http://kurumi.gitee.io/shanks/2019/10/11/swift-function-program/">October 11th 2019</a>
            <p>版权声明：本文采用<a rel="license noopener" href="http://creativecommons.org/licenses/by-nc/4.0/" target="_blank">知识共享署名-非商业性使用 4.0 国际许可协议</a>进行许可</p>
        </div>
    
    <!-- paginator  -->
    <ul class="post-paginator">
        <li class="next">
            
                <div class="nextSlogan">Next Post</div>
                <a href= "/shanks/2020/01/27/how-to-know-highorlow-computer-md/" title= "如何判断机器的字节顺序是高字节在前还是低字节在前">
                    <div class="nextTitle">如何判断机器的字节顺序是高字节在前还是低字节在前</div>
                </a>
            
        </li>
        <li class="previous">
            
                <div class="prevSlogan">Previous Post</div>
                <a href= "/shanks/2019/10/03/how-to-use-functional-program-in-swift/" title= "【译】如何在swift中使用函数式编程">
                    <div class="prevTitle">【译】如何在swift中使用函数式编程</div>
                </a>
            
        </li>
    </ul>
    <!-- 评论插件 -->
    <!-- 来必力City版安装代码 -->

<!-- City版安装代码已完成 -->
    
    
    <!-- gitalk评论 -->

    <!-- utteranc评论 -->

    <!-- partial('_partial/comment/changyan') -->
    <!--PC版-->


    
    

    <!-- 评论 -->
</main>
            <!-- profile -->
            
        </div>
        <footer class="footer footer-unloaded">
    <!-- social  -->
    
    <div class="social">
        
    
        
            
                <a href="mailto:ayaseeri@126.com" class="iconfont-archer email" title=email ></a>
            
        
    
        
            
                <a href="//github.com/esdeath" class="iconfont-archer github" target="_blank" title=github></a>
            
        
    
        
    
        
    

    </div>
    
    <!-- powered by Hexo  -->
    <div class="copyright">
        <span id="hexo-power">Powered by <a href="https://hexo.io/" target="_blank">Hexo</a></span><span class="iconfont-archer power">&#xe635;</span><span id="theme-info">theme <a href="https://github.com/fi3ework/hexo-theme-archer" target="_blank">Archer</a></span>
    </div>
    <!-- 不蒜子  -->
    
    <div class="busuanzi-container">
    
     
    <span id="busuanzi_container_site_pv">PV: <span id="busuanzi_value_site_pv"></span> :)</span>
    
    </div>
    
</footer>
    </div>
    <!-- toc -->
    
    <div class="toc-wrapper" style=
    







top:50vh;

    >
        <div class="toc-catalog">
            <span class="iconfont-archer catalog-icon">&#xe613;</span><span>CATALOG</span>
        </div>
        <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#介绍"><span class="toc-number">1.</span> <span class="toc-text">介绍</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#什么是函数式编程"><span class="toc-number">1.1.</span> <span class="toc-text">什么是函数式编程</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#函数式工具"><span class="toc-number">2.</span> <span class="toc-text">函数式工具</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#例子"><span class="toc-number">3.</span> <span class="toc-text">例子</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#“AND”类型"><span class="toc-number">4.</span> <span class="toc-text">“AND”类型</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#“OR”-Type-Sum"><span class="toc-number">5.</span> <span class="toc-text">“OR” Type (Sum)</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#这个课程"><span class="toc-number">6.</span> <span class="toc-text">这个课程</span></a></li></ol>
    </div>
    
    <div class="back-top iconfont-archer">&#xe639;</div>
    <div class="sidebar sidebar-hide">
    <ul class="sidebar-tabs sidebar-tabs-active-0">
        <li class="sidebar-tab-archives"><span class="iconfont-archer">&#xe67d;</span><span class="tab-name">Archive</span></li>
        <li class="sidebar-tab-tags"><span class="iconfont-archer">&#xe61b;</span><span class="tab-name">Tag</span></li>
        <li class="sidebar-tab-categories"><span class="iconfont-archer">&#xe666;</span><span class="tab-name">Cate</span></li>
    </ul>
    <div class="sidebar-content sidebar-content-show-archive">
          <div class="sidebar-panel-archives">
    <!-- 在ejs中将archive按照时间排序 -->
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    <div class="total-and-search">
        <div class="total-archive">
        Total : 16
        </div>
        <!-- search  -->
        
    </div>
    
    <div class="post-archive">
    
    
    
    
    <div class="archive-year"> 2020 </div>
    <ul class="year-list">
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">08/29</span><a class="archive-post-title" href= "/shanks/2020/08/29/flutter-ios-plugin-delegate-error/" >Flutter中针对iOS封装Plugin组件注意事项</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">08/29</span><a class="archive-post-title" href= "/shanks/2020/08/29/flutter-mvvm/" >Flutter中使用Provider实现MVVM架构</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">06/07</span><a class="archive-post-title" href= "/shanks/2020/06/07/crypt-night/" >9.SSL/TLS(为了更安全的通信)---《图解密码学》</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">05/31</span><a class="archive-post-title" href= "/shanks/2020/05/31/crypt-eight/" >8.证书(为公钥加上数字签名)---《图解密码学》</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">05/29</span><a class="archive-post-title" href= "/shanks/2020/05/29/crypt-seven/" >7.数字签名(消息到底是谁写的)---《图解密码学》</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">05/21</span><a class="archive-post-title" href= "/shanks/2020/05/21/crypt-six/" >6.消息认证码(消息被正确传送了吗)---《图解密码学》</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">05/12</span><a class="archive-post-title" href= "/shanks/2020/05/12/crypt-five-md/" >5.单向散列函数(获取消息的指纹)---《图解密码学》</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">05/08</span><a class="archive-post-title" href= "/shanks/2020/05/08/crypt-four-md/" >4.非对称加密(公钥加密,私钥解密)---《图解密码学》</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">05/05</span><a class="archive-post-title" href= "/shanks/2020/05/05/crypt-three-md/" >3. 分组密码的模式(分组密码是如何迭代)---《图解密码学》</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">04/30</span><a class="archive-post-title" href= "/shanks/2020/04/30/crypt-two-md/" >2.对称加密（相同密钥加解密)---《图解密码学》</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">04/29</span><a class="archive-post-title" href= "/shanks/2020/04/29/crypt-one-md/" >1.密码学 ---《图解密码学》</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">03/27</span><a class="archive-post-title" href= "/shanks/2020/03/27/ios-gcd-ptread/" >iOS 90%人可能都会回答错误的一个多线程基础题</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">01/27</span><a class="archive-post-title" href= "/shanks/2020/01/27/how-to-know-highorlow-computer-md/" >如何判断机器的字节顺序是高字节在前还是低字节在前</a>
        </li>
    
    
    
    
    
        </ul>
    
    <div class="archive-year"> 2019 </div>
    <ul class="year-list">
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">10/11</span><a class="archive-post-title" href= "/shanks/2019/10/11/swift-function-program/" >【译】Swift和函数式编程的精髓</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">10/03</span><a class="archive-post-title" href= "/shanks/2019/10/03/how-to-use-functional-program-in-swift/" >【译】如何在swift中使用函数式编程</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">08/28</span><a class="archive-post-title" href= "/shanks/2019/08/28/swift-operator-override/" >【译】如何在swift中使用函数式编程</a>
        </li>
    
    </div>
  </div>
        <div class="sidebar-panel-tags">
    <div class="sidebar-tags-name">
    
    </div>
    <div class="iconfont-archer sidebar-tags-empty">&#xe678;</div>
    <div class="tag-load-fail" style="display: none; color: #ccc; font-size: 0.6rem;">
    缺失模块。<br/>
    1、请确保node版本大于6.2<br/>
    2、在博客根目录（注意不是archer根目录）执行以下命令：<br/>
    <span style="color: #f75357; font-size: 1rem; line-height: 2rem;">npm i hexo-generator-json-content --save</span><br/>
    3、在根目录_config.yml里添加配置：
    <pre style="color: #787878; font-size: 0.6rem;">
jsonContent:
  meta: false
  pages: false
  posts:
    title: true
    date: true
    path: true
    text: false
    raw: false
    content: false
    slug: false
    updated: false
    comments: false
    link: false
    permalink: false
    excerpt: false
    categories: true
    tags: true</pre>
    </div> 
    <div class="sidebar-tags-list"></div>
</div>
        <div class="sidebar-panel-categories">
    <div class="sidebar-categories-name">
    
    </div>
    <div class="iconfont-archer sidebar-categories-empty">&#xe678;</div>
    <div class="sidebar-categories-list"></div>
</div>
    </div>
</div> 
    <script>
    var siteMeta = {
        root: "/shanks/",
        author: "驿路星辰"
    }
</script>
    <!-- CDN failover -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.3.1/dist/jquery.min.js"></script>
    <script type="text/javascript">
        if (typeof window.$ === 'undefined')
        {
            console.warn('jquery load from jsdelivr failed, will load local script')
            document.write('<script src="/shanks/lib/jquery.min.js">\x3C/script>')
        }
    </script>
    <script src="/shanks/scripts/main.js"></script>
    <!-- algolia -->
    
    <!-- busuanzi  -->
    
    <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    
    <!-- CNZZ  -->
    
    </div>
    <!-- async load share.js -->
    
        <script src="/shanks/scripts/share.js" async></script>    
     
    </body>
</html>


